# -*- coding: utf-8 -*-
import uuid


class Initialize():
    def save(self, obj, data: list):
        object_list = []
        for ele in data:
            m2m_dict = {}
            new_data = {}
            for key, value in ele.items():
                # 判断传的 value 为 list 的多对多进行抽离，使用set 进行更新
                if isinstance(value, list) and key != 'steps':
                    m2m_dict[key] = value
                else:
                    if isinstance(value, uuid.UUID):
                        new_data[key] = str(value)
                    else:
                        new_data[key] = value
            object, _ = obj.objects.get_or_create(
                id=ele.get("id"), defaults=new_data)
            for key, m2m in m2m_dict.items():
                m2m = list(set(m2m))
                if m2m and len(m2m) > 0 and m2m[0]:
                    exec(f"""
if object.{key}:
    values_list = object.{key}.all().values_list('id', flat=True)
    values_list = list(set(list(values_list) + {m2m}))
    object.{key}.set(values_list)
""")
            object_list.append(object)
        return object_list
